from django.shortcuts import render,HttpResponse,redirect
from app_user import models
from ..models import Goods,goods_slide_show,goods_type_show, Order, Shopping_Cart, Category,new_product,goods_details,CommentInfo,UserInfo
from django.views.decorators.csrf import csrf_exempt
from app_user.utls.pagenation import Pagenation
from app_user.utls.form import commentadd_ModeForm,RegisterModeForm
import json
from datetime import datetime
from app_user.utls.encrypt import md5




def insert_goods(request):
    """"""
    """批量插入数据"""
    # for i in range(1):
    #     models.Goods.objects.create(title="青岛大虾", price='36', inventory='40000', address="山东青岛", phone="12305078901", img="goods_img/seafood_1.jpg", category_id='2', introduction="吃青岛大虾", sales="9203")
    # for i in range(1):
    #     models.Goods.objects.create(title="澳洲牛排", price='56', inventory='20000', address="澳大利亚",
    #                                 phone="13705078901", img="goods_img/meat_1.jpeg", category_id='3',
    #                                 introduction="very GOOD", sales="703")
    # for i in range(1):
    #     models.Goods.objects.create(title="农家土鸡蛋", price='15', inventory='80000', address="河南",
    #                                 phone="19905068901", img="goods_img/egg_1.jpg", category_id='4',
    #                                 introduction="香香香", sales="8903")
    # for i in range(1):
    #     models.Goods.objects.create(title="上海青", price='12', inventory='60000', address="上海",
    #                                 phone="12704468901", img="goods_img/vegetable_1.jpg", category_id='5',
    #                                 introduction="上霜青菜，软糯香甜", sales="1903")
    # for i in range(1):
    #     models.Goods.objects.create(title="东北水饺", price='28', inventory='30000', address="东北",
    #                                 phone="13675428901", img="goods_img/frozenfood_1.jpg", category_id='6',
    #

    # models.goods_slide_show.objects.create(goods_id="1")
    # models.goods_slide_show.objects.create(goods_id="2")
    # models.goods_slide_show.objects.create(goods_id="5")
    # models.goods_slide_show.objects.create(goods_id="8")
    # models.goods_slide_show.objects.create(goods_id="11")
    # models.goods_slide_show.objects.create(goods_id="14")
    # models.goods_slide_show.objects.create(goods_id="17")
    # models.Goods.objects.create(title="进口柠檬", price='12', inventory='10200', address="新西兰",
    #                                 phone="1704407300", img="goods_img/plum_2.jpg", category_id='1',
    #                                introduction="very GOOD", sales="400")
    # models.Goods.objects.create(title="玫瑰香葡萄", price='10', inventory='25000', address="新疆乌鲁木齐",
    #                             phone="1564308690", img="goods_img/plum_3.jpg", category_id='1',
    #










def home(request):
    """"""
    """商城主页"""

    id = request.session.get('info')['id']
    cart_num = models.Shopping_Cart.objects.filter(user_id=id).count()
    fruit_data = models.Goods.objects.filter(category_id=1,status=1).all()[:4]
    seafood_data = models.Goods.objects.filter(category_id=2,status=1).all()[:4]
    meat_data = models.Goods.objects.filter(category_id=3,status=1).all()[:4]
    egg_data = models.Goods.objects.filter(category_id=4,status=1).all()[:4]
    vegetable_data = models.Goods.objects.filter(category_id=5,status=1).all()[:4]
    frozenfood_data = models.Goods.objects.filter(category_id=6,status=1).all()[:4]

    slide_show_data = models.goods_slide_show.objects.all()
    slide_show_datas = []
    for i in slide_show_data:
        slide_show_datas.append(models.Goods.objects.filter(id=i.goods_id).first())

    data = {
        "fruit_data":fruit_data,
        "seafood_data": seafood_data,
        "meat_data": meat_data,
        "egg_data":egg_data,
        "vegetable_data":vegetable_data,
        "frozenfood_data":frozenfood_data,
        "slide_show_data": slide_show_datas,
        "cart_num": cart_num,


    }
    return render(request, "test.html", context=data)


def detail(request, id):
    """"""
    """商品详情页"""

    commment_data = CommentInfo.objects.filter(goods_id=id).all()
    commment_num = commment_data.count()


    form = commentadd_ModeForm()


    cookies = request.COOKIES.get('goods_cookies','')
    goods_id_list = cookies.split(";")
    if cookies == "":
        cookies = str(id) + ";"
    else:
        if str(id) in goods_id_list:
            goods_id_list.remove(str(id))
            goods_id_list.insert(0, id)
        else:
            goods_id_list.insert(0,str(id))
            if len(goods_id_list) >= 5:
                goods_id_list = goods_id_list[:5]
            cookies = ';'.join(goods_id_list)



    new_goods_obj = models.new_product.objects.all()
    new_goods_data = []
    for item in new_goods_obj:
        goods_obj = models.Goods.objects.filter(id=item.goods_id).first()
        new_goods_data.append(goods_obj)

    ids = request.session.get('info')['id']
    cart_num = models.Shopping_Cart.objects.filter(user_id=ids).all().count()
    goods_data = models.Goods.objects.filter(id=id).first()
    data = {
        "goods_data": goods_data,
        "cart_num": cart_num,
        "new_goods_data": new_goods_data,
        "comment_data": commment_data,
        "comment_num": commment_num,
        "form": form,
    }
    response = render(request, "detail_test.html", context=data)
    response.set_cookie('goods_cookies', cookies)
    return response





def type_list(request, id, sort):
    """"""
    """分类商品页"""
    new_goods_obj = models.new_product.objects.all()
    new_goods_data = []
    for item in new_goods_obj:
        goods_obj = models.Goods.objects.filter(id=item.goods_id).first()
        new_goods_data.append(goods_obj)

    ids = request.session.get('info')['id']
    cart_num = models.Shopping_Cart.objects.filter(user_id=ids).all().count()

    goods_data = models.Goods.objects.filter(category_id=id,status=1).all()
    if sort == 1:
        goods_data = models.Goods.objects.filter(category_id=id,status=1).all().order_by("-price")
    elif sort == 2:
        goods_data = models.Goods.objects.filter(category_id=id,status=1).all().order_by("-sales")
    goods_obj = Pagenation(number_data=goods_data, request=request)
    goods_datas = goods_obj.page_data
    page_string = goods_obj.page_string
    type_title = models.Category.objects.filter(id=id).first().title
    data = {
        "goods_data": goods_datas,
        "cart_num": cart_num,
        "type_id": id,
        "type_name":type_title,
        "page_string": page_string,
        "new_goods_data": new_goods_data,
    }

    return render(request, "type_list.html", context=data)


def add_cart(request):
    """"""
    """加入购物车"""
    num = int(request.GET.get("num"))
    print(num)
    goods_id = request.GET.get("uid")
    price = num * models.Goods.objects.filter(id=goods_id).first().price
    user_id = request.session.get("info")['id']
    models.Shopping_Cart.objects.create(goods_num=num, goods_id=goods_id, user_id=user_id, total=price)
    cart_num = models.Shopping_Cart.objects.filter(user_id=user_id).all().count()

    data = {
        "status": True,
        "cart_num": cart_num,
    }

    return HttpResponse(json.dumps(data))




@csrf_exempt
def check_price(request):
    """"""
    """获取商品单价"""
    goods_id = request.POST.get("id")
    price = models.Goods.objects.filter(id=goods_id).first().price

    data = {
        "price": price,
    }
    json_string = json.dumps(data),
    return HttpResponse(json_string)


def search_goods(request):
    """"""
    """搜索商品"""
    new_goods_obj = models.new_product.objects.all()
    new_goods_data = []
    for item in new_goods_obj:
        goods_obj = models.Goods.objects.filter(id=item.goods_id,status=1).first()
        new_goods_data.append(goods_obj)


    keywords = request.GET.get('keywords')
    ids = request.session.get('info')['id']
    cart_num = models.Shopping_Cart.objects.filter(user_id=ids).all().count()

    goods_data = models.Goods.objects.filter(title__contains=keywords,status=1).all()
    if goods_data.count() == 0:
        for keys in keywords:
            goods_data = models.Goods.objects.filter(title__contains=keys,status=1).all()
            if goods_data.count() != 0:
                break
    goods_obj = Pagenation(number_data=goods_data, request=request)
    goods_datas = goods_obj.page_data
    page_string = goods_obj.page_string
    data = {
        "goods_data": goods_datas,
        "cart_num": cart_num,
        "page_string": page_string,
        "new_goods_data": new_goods_data,
    }


    return render(request, "search_goods.html", context=data)







@csrf_exempt
def comment_add(request, id):
    """"""
    """评论功能"""

    form = commentadd_ModeForm(data=request.POST)

    user_id = request.session.get("info")["id"]
    goods_id = id

    if form.is_valid():
        form.instance.goods_id = goods_id
        form.instance.user_id = user_id
        today = datetime.now()
        form.instance.create_time = today.strftime("%Y-%m-%d")
        form.save()
        data_dict = {
            "status": True,
        }
        return HttpResponse(json.dumps(data_dict))
    else:
        data_dict = {
            "status": False,
            "error": form.errors,
        }
        return HttpResponse(json.dumps(data_dict))

